import {
  PaginationMeta,
  PaginatedResponse,
} from '../interfaces/response.interface';

export interface PaginationOptions {
  page?: number;
  limit?: number;
  maxLimit?: number;
}

export class PaginationUtil {
  private static readonly DEFAULT_PAGE = 1;
  private static readonly DEFAULT_LIMIT = 10;
  private static readonly MAX_LIMIT = 100;

  /**
   * 解析分页参数
   */
  static parse(options: PaginationOptions): {
    page: number;
    limit: number;
    offset: number;
  } {
    let page = Number(options.page) || this.DEFAULT_PAGE;
    let limit = Number(options.limit) || this.DEFAULT_LIMIT;
    const maxLimit = options.maxLimit || this.MAX_LIMIT;

    page = Math.max(1, page);
    limit = Math.max(1, Math.min(limit, maxLimit));

    const offset = (page - 1) * limit;

    return { page, limit, offset };
  }

  /**
   * 创建分页元数据
   */
  static createMeta(
    page: number,
    limit: number,
    total: number,
  ): PaginationMeta {
    const totalPages = Math.ceil(total / limit);

    return {
      page,
      limit,
      total,
      totalPages,
      hasNext: page < totalPages,
      hasPrev: page > 1,
    };
  }

  /**
   * 创建分页响应
   */
  static createResponse<T>(
    items: T[],
    total: number,
    options: PaginationOptions,
  ): PaginatedResponse<T> {
    const { page, limit } = this.parse(options);
    const meta = this.createMeta(page, limit, total);

    return {
      items,
      meta,
    };
  }
}
